<template>
  <el-row class="row-bg" justify="end">
    <el-col :span="2"> <el-button @click="exportToPDF" type="primary">导出PDF</el-button> </el-col>
  </el-row>
  <div ref="pdfContent" class="pdfContentstyle">
    <el-row class="row-bg"> </el-row>
    <el-row class="row-bg" :justify="pdfLayout.title">
      <el-col :span="5" class="title"> {{ pdfData.startExperiment.experiments }}</el-col>
    </el-row>
    <el-row class="row-bg" :justify="pdfLayout.level2title">
      <el-col :span="12">
        <span class="level2title"> 试验日期:</span>
      </el-col>
    </el-row>
    <el-row class="row-bg" :justify="pdfLayout.text">
      <el-col :span="12">
        <span> {{ pdfData.startExperiment.currentTime }} </span>
      </el-col>
    </el-row>
    <el-row class="row-bg" :justify="pdfLayout.level2title">
      <el-col :span="12"> <span class="level2title">试验回路Test circuit:</span> </el-col>
    </el-row>
    <el-row class="row-bg" :justify="pdfLayout.img">
      <el-col :span="12">
        <template v-for="(item, index) in pdfData.startExperiment.temp?.value" :key="index">
          <el-image
            v-if="item.title == '图像'"
            style="height: 230px"
            fit="contain"
            :src="item.value.img"
          />
        </template>
      </el-col>
    </el-row>
    <el-row class="row-bg testEquipment" :justify="pdfLayout.level2title" :gutter="90">
      <el-col :span="12"> <span class="level2title"> 试验设备和测量仪器:</span></el-col>
    </el-row>
    <el-row class="row-bg testEquipment" :justify="pdfLayout.text" :gutter="90">
      <el-col :span="12" :offset="4"> 设备A</el-col>
      <el-col :span="12" :offset="4"> 设备B</el-col>
      <el-col :span="12" :offset="4"> 设备C</el-col>
    </el-row>
    <el-row class="row-bg" :justify="pdfLayout.level2title">
      <el-col :span="12">
        <span class="level2title">描述信息电压为:</span>50 kV，
        <span class="level2title"> 电流为:</span> <span style="color: red"> 151 kA </span> 。
      </el-col>
      <el-col :span="19"></el-col>
    </el-row>
    <el-row class="row-bg" :justify="pdfLayout.table">
      <el-col :span="12">
        <el-table :data="dataField" :cell-style="cellStyle" border style="width: 100%">
          <el-table-column prop="EquipmenName" label="名称" />
          <el-table-column prop="data" label="数据" />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import { useProfileConfigStore } from '@/store'
import { useFormatConfigStore } from '@/store'
import { useStartExperimentStore } from '@/store'
import circuitDiagram from '@/assets/images/circuitDiagram.png'
const formatConfigStore = useFormatConfigStore()
const profileConfigStor = useProfileConfigStore()
const startExperimentStore = useStartExperimentStore()
import { useDataSourceMagStore } from '@/store'

//导出为pdf
import { ref, onMounted } from 'vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

const pdfContent = ref<HTMLElement | null>(null)

interface CellStyleParams {
  row: Record<string, any> // 行数据
  column: { property: string } // 列信息
  rowIndex: number // 行索引
  columnIndex: number // 列索引
}
// 单元格样式处理函数
const cellStyle = ({ row, column, rowIndex, columnIndex }: CellStyleParams) => {
  // 仅处理分数列
  if (column.property === 'data') {
    const value = row[column.property]
    // 确保是数字类型后再比较
    if (typeof value === 'number' && value > 100) {
      return { color: '#ff0000', fontWeight: 'bold' }
    }
  }
}
// 导出为PDF
const exportToPDF = async () => {
  if (!pdfContent.value) {
    console.error('PDF 内容未正确加载，请稍后重试！')
    return
  }

  try {
    // 将DOM转换为图片
    const canvas = await html2canvas(pdfContent.value as HTMLElement, {
      useCORS: true, // 允许跨域图片
      scale: 2, // 提高分辨率
    })

    // 创建PDF实例
    const pdf = new jsPDF('p', 'mm', 'a4')
    const imgData = canvas.toDataURL('image/jpeg', 1.0)

    // 计算图片尺寸适配A4纸
    const imgWidth = 210 // A4宽度mm
    const imgHeight = (canvas.height * imgWidth) / canvas.width

    // 添加图片到PDF
    const pageHeight = pdf.internal.pageSize.getHeight()
    let y = 0
    while (y < imgHeight) {
      pdf.addImage(imgData, 'JPEG', 0, y, imgWidth, imgHeight)
      y += pageHeight - 10 // 留出页脚空间
      if (y < imgHeight) {
        pdf.addPage()
      }
    }

    // 下载PDF
    pdf.save('exported-document.pdf')
  } catch (error) {
    console.error('导出PDF时发生错误:', error)
  }
}

const dataSourceMagStore = useDataSourceMagStore()

interface PdfLayoutType {
  title: 'start' | 'center' | 'end'
  level2title: 'start' | 'center' | 'end' // 限制为合法的 justify 值
  text: 'start' | 'center' | 'end'
  time: 'start' | 'center' | 'end'
  other: 'start' | 'center' | 'end'
  img: 'start' | 'center' | 'end'
  table: 'start' | 'center' | 'end'
}
// 定义 startData 的接口类型
interface StartDataType {
  currentTime?: string // currentTime 是可选的字符串
}

// 定义 formatConfig 的接口类型
interface FormatConfigType {
  type: string
  font: string
  size: string
  location: {
    id: number
    value: string
    label: string
  }
}
// 定义 pdfData 的接口类型
interface PdfDataType {
  formatConfig: FormatConfigType[] // 使用明确的类型
  profileConfig: any // 根据实际数据结构调整类型
  startExperiment: any
  dataSourceMagStore: any[] // 根据实际数据结构调整类型
}
const pdfLayout = ref<PdfLayoutType>({
  title: 'start',
  level2title: 'start',
  text: 'start',
  time: 'start',
  other: 'start',
  img: 'start',
  table: 'start',
})
let pdfData = ref<PdfDataType>({
  formatConfig: [],
  profileConfig: {},
  startExperiment: {},
  dataSourceMagStore: [],
})

onMounted(() => {
  pdfData.value = {
    formatConfig: formatConfigStore.dataSource,
    profileConfig: profileConfigStor.tempData,
    startExperiment: startExperimentStore.startData,
    dataSourceMagStore: dataSourceMagStore.dataFieldMsgData,
  }

  console.log('pdfData1', pdfData)
  let circuitImg = ref(Object.values(startExperimentStore.startData))

  console.log('pdfData2', circuitImg)
  formatConfigStore.dataSource.forEach((item) => {
    const validJustifyValues: ('start' | 'center' | 'end')[] = ['start', 'center', 'end']
    switch (item.type) {
      case '标题':
        pdfLayout.value.title = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      case '二级标题':
        pdfLayout.value.level2title = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      case '文本':
        pdfLayout.value.text = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      case '时间':
        pdfLayout.value.time = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      case '其他':
        pdfLayout.value.other = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      case '图片':
        pdfLayout.value.img = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      case '表格文本':
        pdfLayout.value.table = validJustifyValues.includes(item.location.value as any)
          ? (item.location.value as 'start' | 'center' | 'end')
          : 'start' // 默认值为 'start'
        break
      default:
        break
    }
  })
  // console.log('PDF Content Ref:', pdfContent.value)
  // console.log('pdfLayout', pdfLayout.value)
})

const dataField = [
  {
    EquipmenName: '设备A',
    data: 188,
  },
  {
    EquipmenName: '设备A',
    data: 87,
  },
  {
    EquipmenName: '设备B',
    data: 69,
  },
  {
    EquipmenName: '设备B',
    data: 45,
  },
  {
    EquipmenName: '设备C',
    data: 57,
  },
  {
    EquipmenName: '设备D',
    data: 63,
  },
  {
    EquipmenName: '设备E',
    data: 74,
  },
]
// 定义合法的 justify 值类型
</script>

<style scoped lang="scss">
.pdfContentstyle {
  padding: 0 10px 0 50px;
}
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.testEquipment {
  .el-col {
    padding: 0 0 10px 0;
  }
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.title {
  font-family: '宋体', SimSun, serif; /* 设置字体族 */
  font-size: 36px; /* 一号 = 36px */
  font-weight: bold;
}
.level2title {
  font-family: '宋体', SimSun, serif; /* 设置字体族 */
  font-size: 18px; /* 二号 = 18px */
  font-weight: bold;
}
</style>
